package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController("userDishController")
@RequestMapping("/user/dish")
@Api(tags = "C端-根据分类id查询菜品接口")
public class DishController {

    @Autowired
    private DishService dishService;
    //先导入redis
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/list")
    public Result<List<DishVO>> list(@RequestParam(value = "categoryId") String categoryId){
        //实现缓存
        //查询之前要先构造redis的key，规则：dish_categoryId
        String key = "dish_" + categoryId;
        //1、查询redis中是否存在菜品数据 通过key获取value
        Object o = redisTemplate.opsForValue().get(key);
        log.info("缓存数据：{}",o);
        //强转为集合
        List<DishVO> dishVOList = (List<DishVO>) o;
//       判断缓存数据是否为空
        if (dishVOList !=null && dishVOList.size() > 0) {
            //2、如果存在则直接查询并返回，无需查询数据库
            return Result.success(dishVOList);
        }else {
            //3、如果不存在则查询数据库，将查询到的数据缓存到redis中
            //创建dish对象，用于查询，设置相关查询条件在地上里面
            Dish dish = new Dish();
            dish.setCategoryId(Long.valueOf(categoryId));
            dish.setStatus(StatusConstant.ENABLE);
            List<DishVO>  dishList  = dishService.listWithFlavor(dish);
            //缓存数据
            redisTemplate.opsForValue().set(key,dishList);
            return Result.success(dishList);

        }





    }


}
